package com.zhouyong.netty.handler;

import com.zhouyong.message.RpcRequestMessage;
import com.zhouyong.message.RpcResponseMessage;
import com.zhouyong.netty.util.Utils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author 99Savage
 * @date 2023/3/17 10:16
 */
@Component
@Slf4j
public class CustomizeServerHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext context, RpcRequestMessage message) throws Exception {
        // 实例化response对象
        RpcResponseMessage responseMessage = new RpcResponseMessage();
        responseMessage.setSequenceId(message.getSequenceId());
        try {
            log.info("[channelRead0]服务端接收客户端的信息为: {}", message);
            // 反射获取该接口的实例化对象
            Object instance = Utils.getServiceInstance(Class.forName(message.getInterfaceName()));
            Method method = instance.getClass().getMethod(message.getMethodName(), message.getParameterTypes());
            Object invoke = method.invoke(instance, message.getParameterValue());

            responseMessage.setCode(HttpStatus.OK.value());
            responseMessage.setMessage("success");
            responseMessage.setData(invoke);

        } catch (Exception e) {
            log.error("异常，cause:【】", e);
            responseMessage.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            responseMessage.setMessage("fail");
        }
        // 发送消息
        context.writeAndFlush(responseMessage);
    }
}
